<template>
  <div class="table">
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" size="mini" @click="delAll">批量删除</el-button>
        <el-input v-model="select_word" size="mini" placeholder="请输入用户名" class="handle-input"/>
        <el-button type="primary" size="mini" @click="centerDialogVisible = true">添加用户</el-button>
      </div>
    </div>
    <el-table size="mini" border style="width: 100%" :data="data" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40px">

      </el-table-column>
      <el-table-column label="用户图片" width="110px" align="center">
        <template slot-scope="scope">
          <div class="singer-img">
            <img :src="getUrl(scope.row.avator)" style="width:100%"/>
          </div>
          <el-upload :action="uploadUrl(scope.row.id)" :before-upload="beforeAvatorUpload"
                     :on-success="handleAvatorSuccess">
            <el-button size="mini">更新图片</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120px" align="center"/>
      <el-table-column prop="sex" label="性别" width="50px" align="center">
        <template slot-scope="scope">
          {{changeSex(scope.row.sex)}}
        </template>
      </el-table-column>
      <el-table-column prop="phoneNum" label="手机号" width="120px" align="center"/>
      <el-table-column prop="email" label="电子邮箱" width="240px" align="center"/>

      <el-table-column prop="birth" label="生日" width="120px" align="center">
        <template slot-scope="scope">
          {{attachBirth(scope.row.birth)}}
        </template>
      </el-table-column>
      <el-table-column prop="introduction" label="签名" align="center"/>
      <el-table-column prop="location" label="地区" width="100px" align="center"/>
      <el-table-column label="收藏" width="80" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="getCollect(scope.row.id)">收藏</el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout = "total,prev,pager,next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <el-dialog title="添加新用户" :visible.sync="centerDialogVisible" width="400px" center>
      <el-form :model="registerForm" ref="registerForm" label-width="80px" :rules="rules">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input v-model="registerForm.username" placeholder="用户名"/>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input v-model="registerForm.password" placeholder="密码"/>
        </el-form-item>
        <el-form-item label="性别" size="mini">
          <el-radio-group v-model="registerForm.sex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="phoneNum" label="手机号" size="mini">
          <el-input v-model="registerForm.phoneNum" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱" size="mini">
          <el-input v-model="registerForm.email" placeholder="电子邮箱"></el-input>
        </el-form-item>

        <el-form-item label="生日" size="mini">
          <el-date-picker type="date" placeholder="选择日期" v-model="registerForm.birth" style="width: 100%"/>
        </el-form-item>
        <el-form-item prop="introduction" label="签名" size="mini">
          <el-input v-model="registerForm.introduction" placeholder="签名" type="textarea"/>
        </el-form-item>
        <el-form-item prop="location" label="地区" size="mini">
          <el-input v-model="registerForm.location" placeholder="地区"/>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="addConsumer">
          确定
        </el-button>
        <el-button size="mini" @click="centerDialogVisible = false">
          取消
        </el-button>
    </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="editVisible" width="400px" center>
      <el-form :model="form" ref="form" label-width="80px" :rules="rules">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input v-model="form.username" placeholder="用户名"/>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input v-model="form.password" placeholder="密码"/>
        </el-form-item>
        <el-form-item label="歌手名" size="mini">
          <el-radio-group v-model="form.sex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="phoneNum" label="手机号" size="mini">
          <el-input v-model="form.phoneNum" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱" size="mini">
          <el-input v-model="form.email" placeholder="电子邮箱"></el-input>
        </el-form-item>

        <el-form-item label="生日" size="mini">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.birth" style="width: 100%"/>
        </el-form-item>
        <el-form-item prop="introduction" label="签名" size="mini">
          <el-input v-model="form.introduction" placeholder="签名" type="textarea"/>
        </el-form-item>
        <el-form-item prop="location" label="地区" size="mini">
          <el-input v-model="form.location" placeholder="地区"/>
        </el-form-item>

      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="editSave">
          确定
        </el-button>
        <el-button size="mini" @click="editVisible = false">
          取消
        </el-button>
    </span>
    </el-dialog>

    <el-dialog title="删除用户" :visible.sync="delVisible" width="300px" center>
      <div align="center">
        删除不可恢复，是否确定删除
      </div>
      <span slot="footer">
        <el-button size="mini" @click="deleteRow">
          确定
        </el-button>
        <el-button size="mini" @click="delVisible = false">
          取消
        </el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import {getAllConsumer, setConsumer, updateConsumer, delConsumer, getUserOfId} from '../api/index'
import {mixin} from '../mixins/index'

export default {
  mixins: [mixin],
  name: 'InfoPage',
  data () {
    return {
      // 添加弹窗
      centerDialogVisible: false,
      editVisible: false,
      delVisible: false,
      registerForm: {
        username: '',
        password: '',
        sex: '',
        phoneNum: '',
        email: '',
        birth: '',
        introduction: '',
        location: ''
      },
      form: {
        id: '',
        username: '',
        password: '',
        sex: '',
        phoneNum: '',
        email: '',
        birth: '',
        introduction: '',
        location: ''
      },
      tableData: [],
      tempData: [],
      select_word: '',
      currentPage: 1,
      pageSizes: [5, 10, 20, 50],
      pageSize: 5,
      // 当前选择项
      idx: '',
      // 哪些项已经打勾
      multipleSelection: [],
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        phoneNum: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur'}
        ]
        /* email: [
          {required: true, message: '电子信箱不能为空', trigger: 'blur'},
          {type: 'email', message: '请输入正确的电子邮箱地址', trigger: ['blur', 'change']}
        ],
        introduction: [
          {required: true, message: '请输入签名', trigger: 'blur'}
        ],
        location: [
          {required: true, message: '请输入地区', trigger: 'blur'}
        ] */
      }
    }
  },
  computed: {
    data() {
      return this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
    }
  },
  watch: {
    select_word: function() {
      if (this.select_word === '') {
        this.tableData = this.tempData
      } else {
        this.tableData = []
        for (let item of this.tempData) {
          if (item.username.includes(this.select_word)) {
            this.tableData.push(item)
          }
        }
      }
    }
  },
  created () {
    this.getData()
  },
  methods: {
    handleCurrentChange(current) {
      this.currentPage = current
    },
    uploadUrl(id) {
      return `${this.$store.state.HOST}/singer/updateSongPic?id=${id}`
    },
    getData() {
      this.tableData = []
      this.tableData = []
      getAllConsumer().then(res => {
        console.log(res)
        this.tableData = res.data
        this.tempData = res.data
        this.currentPage = 1
      })
    },
    addConsumer () {
      this.$refs['registerForm'].validate(valid => {
        if (valid) {
          let d = this.registerForm.birth
          let datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() +
            ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
          let params = {
            'username': this.registerForm.username,
            'password': this.registerForm.password,
            'sex': this.registerForm.sex,
            'phoneNum': this.registerForm.phoneNum,
            'email': this.registerForm.email,
            'avator': '/img/user.jpg',
            'birth': datetime,
            'location': this.registerForm.location,
            'introduction': this.registerForm.introduction
          }
          setConsumer(params).then(res => {
            if (res.code === 200) {
              // this.getData()
              this.$message.success('添加成功')
              this.registerForm = ''
            } else {
              this.$message.error('添加失败')
            }
          })
          this.centerDialogVisible = false
          this.timer = setTimeout(() => { // 设置延迟执行
            this.getData()
          }, 1000)
        }
      })
    },
    // 弹出编辑页面
    handleEdit(row) {
      this.editVisible = true
      this.form = {
        id: row.id,
        username: row.username,
        password: row.password,
        sex: row.sex,
        phoneNum: row.phoneNum,
        email: row.email,
        birth: row.birth,
        introduction: row.introduction,
        location: row.location
      }
    },
    // 保存编辑页面修改的数据
    editSave() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let d = new Date(this.form.birth)
          let datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() +
            ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
          let params = {
            'id': this.form.id,
            'username': this.form.username,
            'password': this.form.password,
            'sex': this.form.sex,
            'phoneNum': this.form.phoneNum,
            'email': this.form.email,
            'birth': datetime,
            'location': this.form.location,
            'introduction': this.form.introduction
          }
          updateConsumer(params).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.getData()
              this.$message.success('修改成功')
              this.form = ''
            } else {
              this.$message.error('修改失败')
            }
          })
          this.editVisible = false
        }
      })
    },
    deleteRow() {
      delConsumer(this.idx).then(res => {
        if (res.code === 200) {
          this.getData()
          this.$message.success('删除成功')
        } else {
          this.$message.error('删除失败')
        }
      })
      this.delVisible = false
    },
    getCollect(id) {
      this.$router.push({path: '/Collect', query: {id}})
    }
  }
}
</script>

<style scoped>
  .handle-box {
    margin-bottom: 20px;
  }
  .singer-img{
    width: 100%;
    height: 80px;
    border-radius: 5px;
    margin-bottom: 5px;
    overflow: hidden;
  }
  .handle-input{
    width: 300px;
    display: inline-block;
  }
  .pagination{
    display: flex;
    justify-content: center;
  }
</style>
